package com.springboot.test.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.springboot.test.common.enums.ErrorCode;
import com.springboot.test.common.enums.StaticKey;
import com.springboot.test.common.exception.BizException;
import com.springboot.test.entity.UserEntity;
import com.springboot.test.service.param.RegisterParam;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import wiremock.org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Service
@Slf4j
public class RegisterService {

    @Resource
    private RedisService redisService;

    @Resource
    private UserService userService;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    public Boolean register(RegisterParam param){
        //验证用户是否存在
        UserEntity userEntity = userService.queryOneByIdOrPhone(param.getUserId(), param.getPhone());
        if(userEntity != null){
            throw new BizException(ErrorCode.USER_ID_PHONE_EXIST);
        }
        //验证用户验证码是否正确
        if(StringUtils.isBlank(redisService.get(StaticKey.REGISTER_PHONE + ":" + param.getPhone())) ||
                !param.getRegisterCode().equals(redisService.get(StaticKey.REGISTER_PHONE + ":" + param.getPhone()))){
            throw new BizException(ErrorCode.REGISTER_CODE_DISABLED);
        }
        userEntity = new UserEntity();
        userEntity.setUserName(param.getName());
        userEntity.setNickName(param.getNickName());
        userEntity.setUserId(param.getUserId());
        userEntity.setAvatar("https://nbut-business.oss-cn-hangzhou.aliyuncs.com/12c954518bb74edf841ca50a3e55d349013394d9e91a0f27d7c2090df4cf437c.jpeg");
        userEntity.setPassword(DigestUtils.md5DigestAsHex(param.getPassword().getBytes(StandardCharsets.UTF_8)));
        userEntity.setEmail(param.getEmail());
        userEntity.setPhone(param.getPhone());
        userService.save(userEntity);
        return true;
    }

    public void send(String phone){
        String s = sendSms(phone);
        redisService.expireMin(StaticKey.REGISTER_PHONE + ":" + phone,s,StaticKey.REGISTER_TIME);
    }


    public String sendSms(String phone) {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                //.securityToken("<your-token>") // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String s = String.valueOf(code);
        HashMap<String,String> data = new HashMap<>();
        data.put("code",s);
        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("董浩斌个人项目")
                .templateCode("SMS_274665757")
                .phoneNumbers(phone)
                .templateParam(JSONObject.toJSONString(data))
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        log.info("阿里云返回参数:{}",JSONObject.toJSONString(resp));
        // Asynchronous processing of return values
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/

        // Finally, close the client
        client.close();

        return s;
    }
}
